<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="theme-color" content="#33474d">
	<title>失落的乐章</title>
	<link rel="stylesheet" href="/css/style.css" />
	
      <link rel="alternate" href="/atom.xml" title="失落的乐章" type="application/atom+xml">
    
</head>

<body>

	<header class="header">
		<nav class="header__nav">
			
				<a href="/archives" class="header__link">Archive</a>
			
				<a href="/tags" class="header__link">Tags</a>
			
				<a href="/atom.xml" class="header__link">RSS</a>
			
		</nav>
		<h1 class="header__title"><a href="/">失落的乐章</a></h1>
		<h2 class="header__subtitle">技术面前，永远都是学生。</h2>
	</header>

	<main>
		
	<span class="different-posts different-posts_earlier">📖 <a href="/page/23">earlier posts</a> 📖</span>




	<article>
	
		<h1><a href="/2017/10/12/Nginx/30. nginx的负载均衡和反向代理/">nginx的负载均衡和反向代理</a></h1>
	
	<div class="article__infos">
		<span class="article__date">2017-10-12</span><br />
		
		
			<span class="article__tags">
			  	<a class="article__tag-link" href="/tags/Nginx/">Nginx</a>
			</span>
		
	</div>

	

	
		<h2 id="负载均衡模块upstream："><a href="#负载均衡模块upstream：" class="headerlink" title="负载均衡模块upstream："></a>负载均衡模块upstream：</h2><p><figure class="figure"><img src="https://github.com/hcldirgit/image/blob/master/nginx%E7%9A%84%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E5%92%8C%E5%8F%8D%E5%90%91%E4%BB%A3%E7%90%86/01.png?raw=true" alt=""></figure></p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;nginx的负载均衡的算法：</p>
<ol>
<li>轮询（默认）</li>
<li>weight 权重轮询</li>
<li>ip_hash  每个请求按访问ip的hash结果分配，这样来自同一个ip的请求固定到后台的一段服务器上，有效的解决动态网页存在的session共享问题</li>
<li>fair 根据服务器的相应时间短来进行负载，需要安装nginx的upstream_fair模块</li>
<li>url_hash 根据url的hash结果分配，同一个url定向到同一后台服务器，提高缓存服务器的效率，需要安装nginx的hash包</li>
</ol>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;注意：当负载均衡的算法是ip_hash时，后端服务器的在负载均衡的调度中的状态不是weight和backup</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;例如：  </p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">upstream bakend &#123;  </div><div class="line">ip_hash;  </div><div class="line">server 192.168.0.14:88;  </div><div class="line">server 192.168.0.15:80;  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;常用到的状态有：</p>
<ul>
<li>down， 表示server暂时不参与负载均衡</li>
<li>backup 备份机器</li>
<li>max_fails：应许请求失败的次数，默认为1，当超过最大次数是，返回proxy_next_upstream模块定义的错误</li>
<li>fail_timeout：经历了max_fails次失败后， 暂停服务的时间，max_fails可以和fail_timeout一起使用</li>
</ul>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<strong>nginx对后端服务器的检查能力较弱，仅限于端口检查！</strong></p>
<h2 id="反向代理模块proxy："><a href="#反向代理模块proxy：" class="headerlink" title="反向代理模块proxy："></a>反向代理模块proxy：</h2><p><figure class="figure"><img src="https://github.com/hcldirgit/image/blob/master/nginx%E7%9A%84%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E5%92%8C%E5%8F%8D%E5%90%91%E4%BB%A3%E7%90%86/02.png?raw=true" alt=""></figure></p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;proxy_pass:http:url1要和upstream模块的url1对应；否则没法实现；</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;expires   过期时间：0为不过期</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;下面介绍http proxy模块中的相关指令：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">proxy_next_upstream</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;语法： </p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">proxy_next_upstream [error|timeout|invalid_header|http_500|http_502|http_503|http_504|http_404|off]</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;确定在何种情况下请求将转发到下一个服务器。转发请求只发生在没有数据传递到客户端的过程中。</p>
<ul>
<li><p>max_fails 允许请求失败的次数默认为1。当超过最大次数时，返回proxy_next_upstream 模块定义的错误</p>
</li>
<li><p>proxy_connect<em>timeout 后端服务器连接的超时时间</em>发起握手等候响应超时时间</p>
</li>
<li><p>proxy_read<em>timeout 连接成功后</em>等候后端服务器响应时间_其实已经进入后端的排队之中等候处理（也可以说是后端服务器处理请求的时间）</p>
</li>
<li><p>proxy_send<em>timeout 后端服务器数据回传时间</em>就是在规定时间之内后端服务器必须传完所有的数据</p>
</li>
<li><p>proxy_pass 这个指令设置被代理服务器的地址和被映射的URI</p>
</li>
</ul>

	

	

</article>




	<article>
	
		<h1><a href="/2017/10/12/Nginx/3. Apache和Nginx运行原理解析/">Apache和Nginx运行原理解析</a></h1>
	
	<div class="article__infos">
		<span class="article__date">2017-10-12</span><br />
		
		
			<span class="article__tags">
			  	<a class="article__tag-link" href="/tags/LNMP/">LNMP</a> <a class="article__tag-link" href="/tags/Nginx/">Nginx</a>
			</span>
		
	</div>

	

	
		<h2 id="Web服务器"><a href="#Web服务器" class="headerlink" title="Web服务器"></a>Web服务器</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Web服务器也称为WWW(WORLD WIDE WEB)服务器，主要功能是提供网上信息浏览服务。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;应用层使用HTTP协议。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;HTML文档格式。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;浏览器统一资源定位器(URL)。<br>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Web服务器常常以B/S（Browser/Server）方式提供服务。浏览器和服务器的交互方式如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">GET /index.php HTTP/1.1</div><div class="line"></div><div class="line">+---------------+                   +----------------+</div><div class="line">|               +-------------------&gt;                |</div><div class="line">|   Browser     |                   |   Server       |</div><div class="line">|               &lt;-------------------+                |</div><div class="line">+---------------+                   +----------------+</div><div class="line"></div><div class="line">                  HTTP/1.1 200 OK</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;浏览器向服务器发出HTTP请求(Request)。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;服务器收到浏览器的请求数据，经过分析处理，向浏览器输出响应数据（Response）。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;浏览器收到服务器的响应数据，经过分析处理，将最终结果显示在浏览器中。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Apache和Nginx都属于Web服务器，两者都实现了HTTP 1.1协议。</p>
<h2 id="Apache-概述"><a href="#Apache-概述" class="headerlink" title="Apache 概述"></a>Apache 概述</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Apache HTTP Server是Apache软件基金会的一个开放源代码的网页服务器，可以在大多数计算机操作系统中运行，由于其跨平台和安全性。被广泛使用，是最流行的Web服务器端软件之一。它快速、可靠并且可通过简单的API扩充，将Perl／Python等解释器编译到服务器中。 – 维基百科</p>
<h3 id="Apache组件"><a href="#Apache组件" class="headerlink" title="Apache组件"></a>Apache组件</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Apache是基于模块化设计的，它的核心代码并不多，大多数的功能都被分散到各个模块中，各个模块在系统启动的时候按需载入。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="string">"text"</span>&gt;         +----------+</div><div class="line">      +- | Module   | -----------------+</div><div class="line">      |  +----------+                  |</div><div class="line">      |                          +------------+</div><div class="line">+-----------+   Apache HTTPD     | php module |</div><div class="line">| Module    |                    +------------+</div><div class="line">+-----------+              +----------+|</div><div class="line">      +----------+-------- |  MPM     |+</div><div class="line">                 |         +----+---+-+</div><div class="line">               +-v-----------+  |   |</div><div class="line">               |    ARP      &lt;--+   |</div><div class="line">               +------+------+      |</div><div class="line">                      |             |</div><div class="line">      +---------------v-------------v--+</div><div class="line">      |      Operating  System         |</div><div class="line">      +--------------------------------+</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;MPM（Multi -Processing Modules，多重处理模块）是Apache的核心组件之一，Apache通过MPM来使用操作系统的资源，对进程和线程池进行管理。Apache为了能够获得最好的运行性能，针对不同的平台 (Unix/Linux、Window)做了优化，为不同的平台提供了不同的MPM，用户可以根据实际情况进行选择，其中最常使用的MPM有 prefork和worker两种。至于您的服务器正以哪种方式运行，取决于安装Apache过程中指定的MPM编译参数,在X系统上默认的编译参数为 prefork。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;由于大多数的Unix都不支持真正的线程，所以采用了预派生子进程(prefork)方式，象Windows或者Solaris这些支持 线程的平台，基于多进程多线程混合的worker模式是一种不错的选择。Apache中还有一个重要的组件就是APR（Apache portable Runtime Library），即Apache可移植运行库，它是一个对操作系统调用的抽象库，用来实现Apache内部组件对操作系统的使用，提高系统的可移植性。 Apache对于php的解析，就是通过众多Module中的php Module来完成的。</p>
<h3 id="Apache生命周期"><a href="#Apache生命周期" class="headerlink" title="Apache生命周期"></a>Apache生命周期</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line"><span class="string">"text"</span>&gt;   +--------------------------------------------------------------+</div><div class="line">   |                 +---------------------+       启动阶段        |</div><div class="line">   |                 |    系统启动, 配置     |                      |</div><div class="line">   |                 +----------+----------+                      |</div><div class="line">   |                            |                                 |</div><div class="line">   |                 +----------v----------+                      |</div><div class="line">   |                 |      模块的初始化     |                      |</div><div class="line">   |                 +-+--------+--------+-+                      |</div><div class="line">   |                   |        |        |                        |</div><div class="line">   |   +-------------+ | +------v-------+| +--------------+       |</div><div class="line">   |   | 子进程初始化  |&lt;+ | 子进程初始化   |+&gt;|  子进程初始化  |       |</div><div class="line">   |   +------+------+   +-------+------+  +-------+------+       |</div><div class="line">   +--------------------------------------------------------------+</div><div class="line">   |          |                  |                 |     运行阶段  |</div><div class="line">   |     +----v----+        +----v----+       +----v----+         |</div><div class="line">   |     | 请求循环 |        |  请求循环 |       | 请求循环 |         |</div><div class="line">   |     +----+----+        +----+----+       +----+----+         |</div><div class="line">   |          |                  |                 |              |</div><div class="line">   |   +------v------+    +------v------+   +------v------+       |</div><div class="line">   |   |  子进程结束   |    |  子进程结束  |   |   子进程结束  |       |</div><div class="line">   |   +-------------+    +-------------+   +-------------+       |</div><div class="line">   +--------------------------------------------------------------+</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这个生命周期是在perfork工作下的示意，从图中可以看出，Apache对于每一个请求都要启动一个单独的进程来处理。</p>
<h3 id="Apache的工作模式-prefork的工作原理"><a href="#Apache的工作模式-prefork的工作原理" class="headerlink" title="Apache的工作模式 prefork的工作原理"></a>Apache的工作模式 prefork的工作原理</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;一个单独的控制进程(父进程)负责产生子进程，这些子进程用于监听请求并作出应答。Apache总是试图保持一些备用的 (spare)或是空闲的子进程用于迎接即将到来的请求。这样客户端就无需在得到服务前等候子进程的产生。在Unix系统中，父进程通常以root身份运行以便邦定80端口，而 Apache产生的子进程通常以一个低特权的用户运行。User和Group指令用于配置子进程的低特权用户。运行子进程的用户必须要对他所服务的内容有读取的权限，但是对服务内容之外的其他资源必须拥有尽可能少的权限。</p>
<h3 id="worker的工作原理"><a href="#worker的工作原理" class="headerlink" title="worker的工作原理"></a>worker的工作原理</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;每个进程能够拥有的线程数量是固定的。服务器会根据负载情况增加或减少进程数量。一个单独的控制进程(父进程)负责子进程的建立。每个子进程能够建立ThreadsPerChild数量的服务线程和一个监听线程，该监听线程监听接入请求并将其传递给服务线程处理和应答。Apache总是试图维持一个备用(spare)或是空闲的服务线程池。这样，客户端无须等待新线程或新进程的建立即可得到处理。在Unix中，为了能够绑定80端口，父进程一般都是以root身份启动，随后，Apache以较低权限的用户建立子进程和线程。User和Group指令用于配置Apache子进程的权限。虽然子进程必须对其提供的内容拥有读权限，但应该尽可能给予他较少的特权。另外，除非使用了suexec ，否则，这些指令配置的权限将被CGI脚本所继承。</p>
<h3 id="Apache的运行-启动阶段"><a href="#Apache的运行-启动阶段" class="headerlink" title="Apache的运行 启动阶段"></a>Apache的运行 启动阶段</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在启动阶段，Apache主要进行配置文件解析(例如http.conf以及Include指令设定的配置文件等)、模块加载(例如modphp.so,modperl.so等)和系统资源初始化（例如日志文件、共享内存段等）工作。在这个阶段，Apache为了获得系统资源最大的使用权限，将以特权用户root（X系统）或超级管理员administrator(Windows系统)完成启动。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这个过程可以通过下图来深入了解：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="string">"text"</span>&gt;       +--------+</div><div class="line">       |  开始   |</div><div class="line">       +----+---+</div><div class="line">            |</div><div class="line"> +----------v------------+   解析主配置文件http.conf中配置信息，</div><div class="line"> |     解析配置文件        |   像LoadModule, AddType</div><div class="line"> +----------+------------+   等指令被加载至内存</div><div class="line">            |</div><div class="line"> +----------v------------+   依据AddModule, LoadModule等指令</div><div class="line"> |   加载静态/动态模块      |   加载Apache模块，像mod_php5.so被</div><div class="line"> +----------+------------+   加载至内存，映射到Apache地址空间。</div><div class="line">            |</div><div class="line"> +----------v------------+   日志文件、共享内存段，数据库链接</div><div class="line"> |     系统资源初始化      |    等初始化</div><div class="line"> +----------+------------+</div><div class="line">            |</div><div class="line">        +---v----+</div><div class="line">        |  结束   |</div><div class="line">        +--------+</div></pre></td></tr></table></figure>
<h3 id="运行阶段"><a href="#运行阶段" class="headerlink" title="运行阶段"></a>运行阶段</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在运行阶段，Apache主要工作是处理用户的服务请求。在这个阶段，Apache放弃特权用户级别，使用普通权限，这主要是基于安全性的考虑，防止由于代码的缺陷引起的安全漏洞。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;由于Apache的Hook机制，Apache 允许模块(包括内部模块和外部模块，例如mod_php5.so,mod_perl.so等)将自定义的函数注入到请求处理循环中。mod_php5.so/php5apache2.dll就是将所包含的自定义函数，通过Hook机制注入到Apache中，在Apache处理流程的各个阶段负责处理php请求。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Apache将请求处理循环分为11个阶段，依次是：Post-Read-Request，URI Translation，Header Parsing，Access Control，Authentication，Authorization，MIME Type Checking，FixUp，Response，Logging，CleanUp。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Apache处理http请求的生命周期:</p>
<p><figure class="figure"><img src="https://github.com/hcldirgit/image/blob/master/Apache%E5%92%8CNginx%E8%BF%90%E8%A1%8C%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90/01.jpg?raw=true" alt=""></figure></p>
<ul>
<li>Post-Read-Request阶段:在正常请求处理流程中，这是模块可以插入钩子的第一个阶段。对于那些想很早进入处理请求的模块来说，这个阶段可以被利用。</li>
<li>URI Translation阶段 : Apache在本阶段的主要工作：将请求的URL映射到本地文件系统。模块可以在这阶段插入钩子，执行自己的映射逻辑。mod_alias就是利用这个阶段工作的。</li>
<li>Header Parsing阶段 : Apache在本阶段的主要工作：检查请求的头部。由于模块可以在请求处理流程的任何一个点上执行检查请求头部的任务，因此这个钩子很少被使用。mod_setenvif就是利用这个阶段工作的。</li>
<li>Access Control阶段 : Apache在本阶段的主要工作：根据配置文件检查是否允许访问请求的资源。Apache的标准逻辑实现了允许和拒绝指令。modauthzhost就是利用这个阶段工作的。</li>
<li>Authentication阶段 : Apache在本阶段的主要工作：按照配置文件设定的策略对用户进行认证，并设定用户名区域。模块可以在这阶段插入钩子，实现一个认证方法。</li>
<li>Authorization阶段 : Apache在本阶段的主要工作：根据配置文件检查是否允许认证过的用户执行请求的操作。模块可以在这阶段插入钩子，实现一个用户权限管理的方法。</li>
<li>MIME Type Checking阶段 : Apache在本阶段的主要工作：根据请求资源的MIME类型的相关规则，判定将要使用的内容处理函数。标准模块modnegotiation和modmime实现了这个钩子。</li>
<li>FixUp阶段 : 这是一个通用的阶段，允许模块在内容生成器之前，运行任何必要的处理流程。和PostReadRequest类似，这是一个能够捕获任何信息的钩子，也是最常使用的钩子。</li>
<li>Response阶段 : Apache在本阶段的主要工作：生成返回客户端的内容，负责给客户端发送一个恰当的回复。这个阶段是整个处理流程的核心部分。</li>
<li>Logging阶段 : Apache在本阶段的主要工作：在回复已经发送给客户端之后记录事务。模块可能修改或者替换Apache的标准日志记录。</li>
<li>CleanUp阶段 : Apache在本阶段的主要工作：清理本次请求事务处理完成之后遗留的环境，比如文件、目录的处理或者Socket的关闭等等，这是Apache一次请求处理的最后一个阶段。</li>
</ul>
<h2 id="Nginx-概述"><a href="#Nginx-概述" class="headerlink" title="Nginx 概述"></a>Nginx 概述</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx（发音同engine x）是一款由俄罗斯程序员Igor Sysoev所开发轻量级的网页服务器、反向代理服务器以及电子邮件（IMAP/POP3）代理服务器。起初是供俄国大型的门户网站及搜索引擎Rambler（俄语：Рамблер）使用。 – 维基百科</p>
<h3 id="Nginx的模块与工作原理"><a href="#Nginx的模块与工作原理" class="headerlink" title="Nginx的模块与工作原理"></a>Nginx的模块与工作原理</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx由内核和模块组成，其中，内核的设计非常微小和简洁，完成的工作也非常简单，仅仅通过查找配置文件将客户端请求映射到一个location block（location是Nginx配置中的一个指令，用于URL匹配），而在这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx的模块从结构上分为核心模块、基础模块和第三方模块：</p>
<ul>
<li>核心模块：HTTP模块、EVENT模块和MAIL模块</li>
<li>基础模块：HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块，</li>
<li>第三方模块：HTTP Upstream Request Hash模块、Notice模块和HTTP Access Key模块。</li>
</ul>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx的模块从功能上分为如下三类:</p>
<ul>
<li>Handlers（处理器模块）。此类模块直接处理请求，并进行输出内容和修改headers信息等操作。Handlers处理器模块一般只能有一个。</li>
<li>Filters （过滤器模块）。此类模块主要对其他处理器模块输出的内容进行修改操作，最后由Nginx输出。</li>
<li>Proxies （代理类模块）。此类模块是Nginx的HTTP Upstream之类的模块，这些模块主要与后端一些服务比如FastCGI等进行交互，实现服务代理和负载均衡等功能。</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="string">"text"</span>&gt;                     +                    ^</div><div class="line">        Http Request |                    |  Http Response</div><div class="line">                     |                    |</div><div class="line">    +---------+------v-----+         +----+----+</div><div class="line">    |  Conf   | Nginx Core |         | FilterN |</div><div class="line">    +---------+------+-----+         +----^----+</div><div class="line">                     |                    |</div><div class="line">                     |               +----+----+</div><div class="line">                     |               | Filter2 |</div><div class="line">choose a handler     |               +----^----+</div><div class="line">based conf           |                    |</div><div class="line">                     |               +----+----+</div><div class="line">                     |               | Filter1 |</div><div class="line">                     |               +----^----+</div><div class="line">                     |                    | Generate content</div><div class="line">               +-----v--------------------+----+</div><div class="line">               |           Handler             |</div><div class="line">               +-------------------------------+</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx本身做的工作实际很少，当它接到一个HTTP请求时，它仅仅是通过查找配置文件将此次请求映射到一个location block，而此location中所配置的各个指令则会启动不同的模块去完成工作，因此模块可以看做Nginx真正的劳动工作者。通常一个location中的指令会涉及一个handler模块和多个filter模块（当然，多个location可以复用同一个模块）。handler模块负责处理请求，完成响应内容的生成，而filter模块对响应内容进行处理。</p>
<h3 id="Nginx架构及工作流程"><a href="#Nginx架构及工作流程" class="headerlink" title="Nginx架构及工作流程"></a>Nginx架构及工作流程</h3><p><figure class="figure"><img src="https://github.com/hcldirgit/image/blob/master/Apache%E5%92%8CNginx%E8%BF%90%E8%A1%8C%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90/02.png?raw=true" alt=""></figure></p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;上图是Nginx的架构，这个架构类似于Apache的Worker工作状态，Nginx的每一个Worker进程都管理着大量的线程，真正处理请求的是Worker之下的线程。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;所有实际上的业务处理逻辑都在worker进程。worker进程中有一个函数，执行无限循环，不断处理收到的来自客户端的请求，并进行处理，直到整个nginx服务被停止。Worker中这个函数执行内容如下：</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;操作系统提供的机制（例如epoll, kqueue等）产生相关的事件。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;接收和处理这些事件，如是接受到数据，则产生更高层的request对象。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;处理request的header和body。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;产生响应，并发送回客户端。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;完成request的处理。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;重新初始化定时器及其他事件。</p>
<h3 id="Nginx和FastCGI-FastCGI"><a href="#Nginx和FastCGI-FastCGI" class="headerlink" title="Nginx和FastCGI FastCGI"></a>Nginx和FastCGI FastCGI</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;FastCGI是一个可伸缩地、高速地在HTTP server和动态脚本语言间通信的接口。多数流行的HTTP server都支持FastCGI，包括Apache、Nginx和lighttpd等。同时，FastCGI也被许多脚本语言支持，其中就有PHP。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;FastCGI是从CGI发展改进而来的。传统CGI接口方式的主要缺点是性能很差，因为每次HTTP服务器遇到动态程序时都需要重新启动脚本解析器来执行解析，然后将结果返回给HTTP服务器。这在处理高并发访问时几乎是不可用的。另外传统的CGI接口方式安全性也很差，现在已经很少使用了。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;FastCGI接口方式采用C/S结构，可以将HTTP服务器和脚本解析服务器分开，同时在脚本解析服务器上启动一个或者多个脚本解析守护进程。当HTTP服务器每次遇到动态程序时，可以将其直接交付给FastCGI进程来执行，然后将得到的结果返回给浏览器。这种方式可以让HTTP服务器专一地处理静态请求或者将动态脚本服务器的结果返回给客户端，这在很大程度上提高了整个应用系统的性能。</p>
<h3 id="Nging和FastCGI合作"><a href="#Nging和FastCGI合作" class="headerlink" title="Nging和FastCGI合作"></a>Nging和FastCGI合作</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx不支持对外部程序的直接调用或者解析，所有的外部程序（包括PHP）必须通过FastCGI接口来调用。FastCGI接口在Linux下是socket（这个socket可以是文件socket，也可以是ip socket）。接下来以Nginx下PHP的运行过程来说明。PHP-FPM是管理FastCGI的一个管理器，它作为PHP的插件存在。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;FastCGI进程管理器php-fpm自身初始化，启动主进程php-fpm和启动start_servers个CGI 子进程。主进程php-fpm主要是管理fastcgi子进程，监听9000端口。fastcgi子进程等待来自Web Server的连接。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;当客户端请求到达Web Server Nginx是时，Nginx通过location指令，将所有以php为后缀的文件都交给127.0.0.1:9000来处理，即Nginx通过location指令，将所有以php为后缀的文件都交给127.0.0.1:9000来处理。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;FastCGI进程管理器PHP-FPM选择并连接到一个子进程CGI解释器。Web server将CGI环境变量和标准输入发送到FastCGI子进程。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;FastCGI子进程完成处理后将标准输出和错误信息从同一连接返回Web Server。当FastCGI子进程关闭连接时，请求便告处理完成。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;FastCGI子进程接着等待并处理来自FastCGI进程管理器（运行在 WebServer中）的下一个连接。</p>
<h2 id="Apache和Nginx比较-功能对比"><a href="#Apache和Nginx比较-功能对比" class="headerlink" title="Apache和Nginx比较 功能对比"></a>Apache和Nginx比较 功能对比</h2><ul>
<li><p>Nginx和Apache一样，都是HTTP服务器软件，在功能实现上都采用模块化结构设计，都支持通用的语言接口，如PHP、Perl、Python等，同时还支持正向和反向代理、虚拟主机、URL重写、压缩传输、SSL加密传输等。</p>
</li>
<li><p>在功能实现上，Apache的所有模块都支持动、静态编译，而Nginx模块都是静态编译的，</p>
</li>
<li><p>对FastCGI的支持，Apache对Fcgi的支持不好，而Nginx对Fcgi的支持非常好；</p>
</li>
<li><p>在处理连接方式上，Nginx支持epoll，而Apache却不支持；</p>
</li>
<li><p>在空间使用上，Nginx安装包仅仅只有几百K，和Nginx比起来Apache绝对是庞然大物。</p>
</li>
</ul>
<h2 id="Nginx相对Apache的优点"><a href="#Nginx相对Apache的优点" class="headerlink" title="Nginx相对Apache的优点"></a>Nginx相对Apache的优点</h2><ul>
<li><p>轻量级，同样起web 服务，比apache 占用更少的内存及资源</p>
</li>
<li><p>静态处理，Nginx 静态处理性能比 Apache 高 3倍以上</p>
</li>
<li><p>抗并发，nginx 处理请求是异步非阻塞的，而apache则是阻塞型的，在高并发下nginx 能保持低资源低消耗高性能。在Apache+PHP（prefork）模式下，如果PHP处理慢或者前端压力很大的情况下，很容易出现Apache进程数飙升，从而拒绝服务的现象。</p>
</li>
<li><p>高度模块化的设计，编写模块相对简单</p>
</li>
<li><p>社区活跃，各种高性能模块出品迅速啊</p>
</li>
</ul>
<h2 id="Apache相对Nginx的优点"><a href="#Apache相对Nginx的优点" class="headerlink" title="Apache相对Nginx的优点"></a>Apache相对Nginx的优点</h2><ul>
<li><p>;rewrite，比nginx 的rewrite 强大</p>
</li>
<li><p>模块超多，基本想到的都可以找到</p>
</li>
<li><p>少bug，nginx的bug相对较多</p>
</li>
<li><p>超稳定</p>
</li>
<li><p>Apache对PHP支持比较简单，Nginx需要配合其他后端用</p>
</li>
</ul>
<h2 id="选择Nginx的优势所在"><a href="#选择Nginx的优势所在" class="headerlink" title="选择Nginx的优势所在"></a>选择Nginx的优势所在</h2><ul>
<li><p>作为Web服务器: Nginx处理静态文件、索引文件，自动索引的效率非常高。</p>
</li>
<li><p>作为代理服务器，Nginx可以实现无缓存的反向代理加速，提高网站运行速度。</p>
</li>
<li><p>作为负载均衡服务器，Nginx既可以在内部直接支持Rails和PHP，也可以支持HTTP代理服务器对外进行服务，同时还支持简单的容错和利用算法进行负载均衡。</p>
</li>
<li><p>在性能方面，Nginx是专门为性能优化而开发的，在实现上非常注重效率。它采用内核Poll模型(epoll and kqueue )，可以支持更多的并发连接，最大可以支持对50 000个并发连接数的响应，而且只占用很低的内存资源。</p>
</li>
<li><p>在稳定性方面，Nginx采取了分阶段资源分配技术，使得CPU与内存的占用率非常低。Nginx官方表示，Nginx保持10 000个没有活动的连接，而这些连接只占用2.5MB内存，因此，类似DOS这样的攻击对Nginx来说基本上是没有任何作用的。</p>
</li>
<li><p>在高可用性方面，Nginx支持热部署，启动速度特别迅速，因此可以在不间断服务的情况下，对软件版本或者配置进行升级，即使运行数月也无需重新启动，几乎可以做到7×24小时不间断地运行。</p>
</li>
</ul>
<h2 id="同时使用Nginx和Apache"><a href="#同时使用Nginx和Apache" class="headerlink" title="同时使用Nginx和Apache"></a>同时使用Nginx和Apache</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;由于Nginx和Apache各自的优势，现在很多人选择了让两者在服务器中共存。在服务器端让Nginx在前，Apache在后。由Nginx做负载均衡和反向代理，并且处理静态文件，讲动态请求（如PHP应用）交给Apache去处理。</p>

	

	

</article>




	<article>
	
		<h1><a href="/2017/10/12/Nginx/29. nginx中location的规则/">nginx中location的规则</a></h1>
	
	<div class="article__infos">
		<span class="article__date">2017-10-12</span><br />
		
		
			<span class="article__tags">
			  	<a class="article__tag-link" href="/tags/LNMP/">LNMP</a> <a class="article__tag-link" href="/tags/Nginx/">Nginx</a>
			</span>
		
	</div>

	

	
		<h2 id="语法规则"><a href="#语法规则" class="headerlink" title="语法规则"></a>语法规则</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">location [=|~|~*|^~] /uri/ &#123; … &#125;</div></pre></td></tr></table></figure>
<ul>
<li>= 开头表示精确匹配</li>
<li>^~ 开头表示uri以某个常规字符串开头，不是正则匹配。#^~表示普通字符匹配，如果该选项匹配，只匹配该选项，不匹配别的选项，一般用来匹配目录。nginx不对url做编码，因此请求为/static/20%/aa，可以被规则^~ /static/ /aa匹配到（注意是空格）。</li>
<li>~ 开头表示区分大小写的正则匹配</li>
<li>~*  开头表示不区分大小写的正则匹配</li>
<li>!~和!~*分别为区分大小写不匹配及不区分大小写不匹配 的正则</li>
<li>/ 通用匹配，任何请求都会匹配到。</li>
<li>@     #”@” 定义一个命名的 location，使用在内部定向时，例如 error_page, try_files如 error_page, try_files</li>
</ul>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;多个location配置的情况下匹配顺序为：</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;首先匹配 =，其次匹配^~, 其次是按文件中顺序的正则匹配，最后是交给 / 通用匹配。当有匹配成功时候，停止匹配，按当前匹配规则处理请求。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;”@”不能通过外部输入的url匹配<br>~ 这个指正则匹配</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;例子，有如下匹配规则：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line">location = / &#123;精确匹配，必须是127.0.0.1/</div><div class="line"><span class="comment">#规则A</span></div><div class="line">&#125;</div><div class="line">location = /login &#123;精确匹配，必须是127.0.0.1/login</div><div class="line"><span class="comment">#规则B</span></div><div class="line">&#125;</div><div class="line">location ^~ /static/ &#123;非精确匹配，并且不区分大小写，比如127.0.0.1/static/js.</div><div class="line"><span class="comment">#规则C</span></div><div class="line">&#125;</div><div class="line">location ~ .(gif|jpg|png|js|css)$ &#123;区分大小写，以gif,jpg,js结尾</div><div class="line"><span class="comment">#规则D</span></div><div class="line">&#125;</div><div class="line">location ~* .png$ &#123;不区分大小写，匹配.png结尾的</div><div class="line"><span class="comment">#规则E</span></div><div class="line">&#125;</div><div class="line">location !~ .xhtml$ &#123;区分大小写，匹配不已.xhtml结尾的</div><div class="line"><span class="comment">#规则F</span></div><div class="line">&#125;</div><div class="line">location !~* .xhtml$ &#123;</div><div class="line"><span class="comment">#规则G</span></div><div class="line">&#125;</div><div class="line">location / &#123;什么都可以</div><div class="line"><span class="comment">#规则H</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="静态文件不记录日志，配置缓存"><a href="#静态文件不记录日志，配置缓存" class="headerlink" title="静态文件不记录日志，配置缓存"></a>静态文件不记录日志，配置缓存</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$</div><div class="line">&#123;</div><div class="line">        expires      30d;</div><div class="line">        access_log off;</div><div class="line">&#125;</div><div class="line"></div><div class="line">location ~ .*\.(js|css)$</div><div class="line"> &#123;</div><div class="line">        expires      12h;</div><div class="line">        access_log off;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
	

	

</article>




	<article>
	
		<h1><a href="/2017/10/12/Nginx/28. 深入理解PHP之：Nginx 与 FPM 的工作机制/">深入理解PHP之：Nginx 与 FPM 的工作机制</a></h1>
	
	<div class="article__infos">
		<span class="article__date">2017-10-12</span><br />
		
		
			<span class="article__tags">
			  	<a class="article__tag-link" href="/tags/LNMP/">LNMP</a> <a class="article__tag-link" href="/tags/Nginx/">Nginx</a>
			</span>
		
	</div>

	

	
		<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;网络上有很多关于如何配置 Nginx + FPM 的文章，但它们更多从操作的角度出发，告诉我们怎么做，但却没有告诉我们为什么要这么做，本文从 Nginx 与 FPM 的工作机制出发，探讨配置背后的原理，让我们真正理解 Nginx 与 PHP 是如何协同工作的。要说 Nginx 与 PHP 是如何协同工作的，首先得说 CGI (Common Gateway Interface) 和 FastCGI 这两个协议。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;CGI 是 Web Server 与后台语言交互的协议，有了这个协议，开发者可以使用任何语言处理 Web Server 发来的请求，动态的生成内容。但 CGI 有一个致命的缺点，那就是每处理一个请求都需要 fork 一个全新的进程，随着 Web 的兴起，高并发越来越成为常态， 这样低效的方式明显不能满足需求。就这样，FastCGI 诞生了，CGI 很快就退出了历史的 舞台。FastCGI，顾名思义为更快的 CGI，它允许在一个进程内处理多个请求，而不是一个 请求处理完毕就直接结束进程，性能上有了很大的提高。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;至于 FPM (FastCGI Process Manager)，它是 FastCGI 的实现，任何实现了 FastCGI 协议的 Web Server 都能够与之通信。FPM 之于标准的 FastCGI，也提供了一些增强功能，具体可以参考官方文档：PHP: FPM Installation。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;FPM 是一个 PHP 进程管理器，包含 master 进程和 worker 进程两种进程：master 进程只有一个，负责监听端口，接收来自 Web Server 的请求，而 worker 进程则一般有多个 (具体数量根据实际需要配置)，每个进程内部都嵌入了一个 PHP 解释器，是 PHP 代码真正执行的地方，下图是我本机上 fpm 的进程情况，1一个 master 进程，3个 worker 进程：</p>
<p><figure class="figure"><img src="https://github.com/hcldirgit/image/blob/master/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3PHP%E4%B9%8B%EF%BC%9ANginx%20%E4%B8%8E%20FPM%20%E7%9A%84%E5%B7%A5%E4%BD%9C%E6%9C%BA%E5%88%B6/01.png?raw=true" alt=""></figure></p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;从 FPM 接收到请求，到处理完毕，其具体的流程如下：</p>
<ol>
<li>FPM 的 master 进程接收到请求</li>
<li>master 进程根据配置指派特定的 worker 进程进行请求处理，如果没有可用进程，返回错误，这也是我们配合 Nginx 遇到502错误比较多的原因。</li>
<li>worker 进程处理请求，如果超时，返回504错误</li>
<li>请求处理结束，返回结果</li>
</ol>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;FPM 从接收到处理请求的流程就是这样了，那么 Nginx 又是如何发送请求给 fpm 的呢？这就需要从 Nginx 层面来说明了。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;我们知道，Nginx 不仅仅是一个 Web 服务器，也是一个功能强大的 Proxy 服务器，除了进行 http 请求的代理，也可以进行许多其他协议请求的代理，包括本文与 fpm 相关的 fastcgi 协议。为了能够使 Nginx 理解 fastcgi 协议，Nginx 提供了 fastcgi 模块来将 http 请求映射为对应的 fastcgi 请求。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx 的 fastcgi 模块提供了 fastcgi_param 指令来主要处理这些映射关系，下面 Ubuntu 下 Nginx 的一个配置文件，其主要完成的工作是将 Nginx 中的变量翻译成 PHP 中能够理解的变量。</p>
<p><figure class="figure"><img src="https://github.com/hcldirgit/image/blob/master/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3PHP%E4%B9%8B%EF%BC%9ANginx%20%E4%B8%8E%20FPM%20%E7%9A%84%E5%B7%A5%E4%BD%9C%E6%9C%BA%E5%88%B6/02.png?raw=true" alt=""></figure></p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;除此之外，非常重要的就是 fastcgi_pass 指令了，这个指令用于指定 fpm 进程监听的地址，Nginx 会把所有的 php 请求翻译成 fastcgi 请求之后再发送到这个地址。下面一个简单的可以工作的 Nginx 配置文件：</p>
<p><figure class="figure"><img src="https://github.com/hcldirgit/image/blob/master/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3PHP%E4%B9%8B%EF%BC%9ANginx%20%E4%B8%8E%20FPM%20%E7%9A%84%E5%B7%A5%E4%BD%9C%E6%9C%BA%E5%88%B6/03.png?raw=true" alt=""></figure></p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在这个配置文件中，我们新建了一个虚拟主机，监听在 80 端口，Web 根目录为 /home/rf/projects/wordpress。然后我们通过 location 指令，将所有的以 .php 结尾的请求都交给 fastcgi 模块处理，从而把所有的 php 请求都交给了 fpm 处理，从而完成  Nginx 到 fpm 的闭环。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如此以来，Nginx 与 FPM 通信的整个流程应该比较清晰了吧。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;查看php-fpm.conf的配置文件</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">[root@192 etc]<span class="comment"># cat php-fpm.conf |grep -v '^;' |grep -v '^$' |grep -v "^ "</span></div><div class="line">[global]</div><div class="line">[www]</div><div class="line">user = php-fpm</div><div class="line">group = php-fpm</div><div class="line">listen = 127.0.0.1:9000</div><div class="line">pm = dynamic</div><div class="line">pm.max_children = 5</div><div class="line">pm.start_servers = 2</div><div class="line">pm.min_spare_servers = 1</div><div class="line">pm.max_spare_servers = 3</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;慢执行日志</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">slowlog = /path/to/slow.log</div><div class="line">request_slowlog_timeout = 1</div><div class="line"></div><div class="line">open_basedir</div><div class="line">php_admin_value[open_basedir]=/data/www/:/tmp/</div></pre></td></tr></table></figure>

	

	

</article>




	<article>
	
		<h1><a href="/2017/10/12/Nginx/27. Nginx：承受3万并发连接数，胜过Apache 10倍/">Nginx：承受3万并发连接数，胜过Apache 10倍</a></h1>
	
	<div class="article__infos">
		<span class="article__date">2017-10-12</span><br />
		
		
			<span class="article__tags">
			  	<a class="article__tag-link" href="/tags/LNMP/">LNMP</a> <a class="article__tag-link" href="/tags/Nginx/">Nginx</a>
			</span>
		
	</div>

	

	
		<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx是目前比较重要的开源性负载均衡技术，新浪、网易、六间房等很多网站都将Nginx部署进自己的网站系统架构，并解决部分问题。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;本文是关于搭建“Nginx + PHP（FastCGI）”Web服务器的第4篇文章。本系列文章作为国内最早详细介绍 Nginx + PHP 安装、配置、使用的资料之一，为推动 Nginx 在国内的发展产生了积极的作用。</p>
<h2 id="众网站纷纷重视Nginx"><a href="#众网站纷纷重视Nginx" class="headerlink" title="众网站纷纷重视Nginx"></a>众网站纷纷重视Nginx</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这是一篇关于Nginx 0.7.x系列版本的文章，安装、配置方式与第3篇文章相差不大，但配置参数有不同。Nginx 0.7.x系列版本虽然为开发版，但在很多大型网站的生产环境中已经使用。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx (“engine x”) 是一个高性能的 HTTP 和反向代理服务器，也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的，它已经在该站点运行超过两年半了。Igor 将源代码以类BSD许可证的形式发布。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx 超越 Apache 的高性能和稳定性，使得国内使用 Nginx 作为 Web 服务器的网站也越来越多，其中包括新浪博客、新浪播客、网易新闻等门户网站频道，六间房、56.com等视频分享网站，Discuz!官方论坛、水木社区等知名论坛，豆瓣、YUPOO相册、海内SNS、迅雷在线等新兴Web 2.0网站。</p>
<h2 id="Nginx：承受3万并发连接数，胜过Apache-10倍"><a href="#Nginx：承受3万并发连接数，胜过Apache-10倍" class="headerlink" title="Nginx：承受3万并发连接数，胜过Apache 10倍"></a>Nginx：承受3万并发连接数，胜过Apache 10倍</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在高并发连接的情况下，Nginx是Apache服务器不错的替代品。Nginx同时也可以作为7层负载均衡服务器来使用。根据我的测试结果，Nginx 0.7.14 + PHP 5.2.6 (FastCGI) 可以承受3万以上的并发连接数，相当于同等环境下Apache的10倍。<br>根据我的经验，4GB内存的服务器+Apache（prefork模式）一般只能处理3000个并发连接，因为它们将占用3GB以上的内存，还得为系统预留1GB的内存。我曾经就有两台Apache服务器，因为在配置文件中设置的MaxClients为4000，当Apache并发连接数达到3800时，导致服务器内存和Swap空间用满而崩溃。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;而这台 Nginx 0.7.14 + PHP 5.2.6 (FastCGI) 服务器在3万并发连接下，开启的10个 Nginx进程消耗150M内存（15M<em>10=150M），开启的64个php-cgi进程消耗1280M内存 （20M</em>64=1280M），加上系统自身消耗的内存，总共消耗不到2GB内存。如果服务器内存较小，完全可以只开启25个php-cgi进程，这样php-cgi消耗的总内存数才500M。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在3万并发连接下，访问Nginx 0.7.14 + PHP 5.2.6 (FastCGI) 服务器的PHP程序，仍然速度飞快。下图为Nginx的状态监控页面，显示的活动连接数为28457（关于Nginx的监控页配置，会在本文接下来所给出的Nginx配置文件中写明）：</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;生产环境下的两台Nginx + PHP5（FastCGI）服务器，跑多个一般复杂的纯PHP动态程序，单台Nginx + PHP5（FastCGI）服务器跑PHP动态程序的处理能力已经超过“700次请求/秒”，相当于每天可以承受6000万（700<em>60</em>60*24=60480000）的访问量（更多信息见此），而服务器的系统负载也不高：</p>
<h2 id="如何获取相关开源程序？"><a href="#如何获取相关开源程序？" class="headerlink" title="如何获取相关开源程序？"></a>如何获取相关开源程序？</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;安装步骤：</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;（系统要求：Linux 2.6+ 内核，本文中的Linux操作系统为CentOS 5.1，另在RedHat AS4上也安装成功）</p>
<h3 id="一、获取相关开源程序："><a href="#一、获取相关开源程序：" class="headerlink" title="一、获取相关开源程序："></a>一、获取相关开源程序：</h3><ol>
<li>利用CentOS Linux系统自带的yum命令安装、升级所需的程序库（RedHat等其他Linux发行版可从安装光盘中找到这些程序库的RPM包，进行安装）：</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">sudo -s</div><div class="line">LANG=C</div><div class="line">yum -y install gcc gcc-c++ autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel</div></pre></td></tr></table></figure>
<ol>
<li>RedHat等其他Linux发行版可从安装光盘中找到这些程序库的RPM包（事先可通过类似“rpm -qa | grep libjpeg”的命令查看所需的RPM包是否存在，通常是“xxx-devel”不存在，需要安装）。RedHat可以直接利用CentOS的RPM包安装，以下是RPM包下载网址：</li>
</ol>
<ul>
<li>RedHat AS4 &amp; CentOS 4<br><a href="http://mirror.be10.com/centos/4/os/i386/CentOS/RPMS/" target="_blank" rel="external">http://mirror.be10.com/centos/4/os/i386/CentOS/RPMS/</a><br><a href="http://mirror.be10.com/centos/4/os/x86_64/CentOS/RPMS/" target="_blank" rel="external">http://mirror.be10.com/centos/4/os/x86_64/CentOS/RPMS/</a> </li>
<li>RedHat AS5 &amp; CentOS 5<br><a href="http://mirror.be10.com/centos/5/os/i386/CentOS/" target="_blank" rel="external">http://mirror.be10.com/centos/5/os/i386/CentOS/</a><br><a href="http://mirror.be10.com/centos/5/os/x86_64/CentOS/" target="_blank" rel="external">http://mirror.be10.com/centos/5/os/x86_64/CentOS/</a> </li>
<li>RPM包搜索网站<br><a href="http://rpm.pbone.net/" target="_blank" rel="external">http://rpm.pbone.net/</a><br><a href="http://www.rpmfind.net/" target="_blank" rel="external">http://www.rpmfind.net/</a></li>
</ul>
<ol>
<li>下载程序源码包：</li>
</ol>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;本文中提到的所有开源软件为截止到2008年8月28日的最新稳定版。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">mkdir -p /data0/software</div><div class="line"><span class="built_in">cd</span> /data0/software</div><div class="line">wget http://sysoev.ru/nginx/nginx-0.7.14.tar.gz</div><div class="line">wget http://www.php.net/get/php-5.2.6.tar.gz/from/this/mirror</div><div class="line">wget http://php-fpm.anight.org/downloads/head/php-5.2.6-fpm-0.5.8.diff.gz</div><div class="line"><span class="comment">#wget http://dev.mysql.com/get/Downloads/MySQL-5.1/mysql-5.1.26-rc.tar.gz/from/http://mirror.x10.com/mirror/mysql/</span></div><div class="line">wget linux/mysql/mysql-5.1.26-rc.tar.gz<span class="string">"&gt;http://blog.s135.com/soft/linux/mysql/mysql-5.1.26-rc.tar.gz</span></div><div class="line"><span class="string">wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.12.tar.gz</span></div><div class="line"><span class="string">#wget "</span>http://downloads.sourceforge.net/mcrypt/libmcrypt-2.5.8.tar.gz?modtime=1171868460&amp;big_mirror=0<span class="string">"</span></div><div class="line"><span class="string">wget http://mirror.optus.net/sourceforge/m/mc/mcrypt/libmcrypt-2.5.8.tar.gz</span></div><div class="line"><span class="string">#wget "</span>http://downloads.sourceforge.net/mcrypt/mcrypt-2.6.7.tar.gz?modtime=1194463373&amp;big_mirror=0<span class="string">"</span></div><div class="line"><span class="string">wget http://mirror.optus.net/sourceforge/m/mc/mcrypt/mcrypt-2.6.7.tar.gz</span></div><div class="line"><span class="string">wget http://pecl.php.net/get/memcache-2.2.3.tgz</span></div><div class="line"><span class="string">#wget "</span>http://downloads.sourceforge.net/mhash/mhash-0.9.9.tar.gz?modtime=1175740843&amp;big_mirror=0<span class="string">"</span></div><div class="line"><span class="string">wget http://mirror.optus.net/sourceforge/m/mh/mhash/mhash-0.9.9.tar.gz</span></div><div class="line"><span class="string">wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-7.7.tar.gz</span></div><div class="line"><span class="string">wget http://bart.eaccelerator.net/source/0.9.5.3/eaccelerator-0.9.5.3.tar.bz2</span></div></pre></td></tr></table></figure>
<h3 id="二、PHP5安装、配置内容-安装PHP-5-2-6（FastCGI模式）"><a href="#二、PHP5安装、配置内容-安装PHP-5-2-6（FastCGI模式）" class="headerlink" title="二、PHP5安装、配置内容,安装PHP 5.2.6（FastCGI模式）"></a>二、PHP5安装、配置内容,安装PHP 5.2.6（FastCGI模式）</h3><ol>
<li>编译安装PHP 5.2.6所需的支持库：</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line">tar zxvf libiconv-1.12.tar.gz</div><div class="line"><span class="built_in">cd</span> libiconv-1.12/</div><div class="line">./configure --prefix=/usr/<span class="built_in">local</span></div><div class="line">make</div><div class="line">make install</div><div class="line"><span class="built_in">cd</span> ../tar zxvf libmcrypt-2.5.8.tar.gz</div><div class="line"><span class="built_in">cd</span> libmcrypt-2.5.8/</div><div class="line">./configure</div><div class="line">make</div><div class="line">make install</div><div class="line">/sbin/ldconfig</div><div class="line"><span class="built_in">cd</span> libltdl/</div><div class="line">./configure --<span class="built_in">enable</span>-ltdl-install</div><div class="line">make</div><div class="line">make install</div><div class="line"><span class="built_in">cd</span> ../../</div><div class="line">tar zxvf mhash-0.9.9.tar.gz</div><div class="line"><span class="built_in">cd</span> mhash-0.9.9/</div><div class="line">./configure</div><div class="line">make</div><div class="line">make install</div><div class="line"><span class="built_in">cd</span> ../</div><div class="line">cp /usr/<span class="built_in">local</span>/lib/libmcrypt.* /usr/lib</div><div class="line">ln -s /usr/<span class="built_in">local</span>/lib/libmhash.so.2 /usr/lib/libmhash.so.2</div><div class="line">tar zxvf mcrypt-2.6.7.tar.gz</div><div class="line"><span class="built_in">cd</span> mcrypt-2.6.7/</div><div class="line">./configure</div><div class="line">make</div><div class="line">make install</div><div class="line"><span class="built_in">cd</span> ../</div></pre></td></tr></table></figure>
<ol>
<li>编译安装MySQL 5.1.26-rc</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">/usr/sbin/groupadd mysql</div><div class="line">/usr/sbin/useradd -g mysql mysql</div><div class="line">tar zxvf mysql-5.1.26-rc.tar.gz</div><div class="line"><span class="built_in">cd</span> mysql-5.1.26-rc/</div><div class="line">./configure --prefix=/usr/<span class="built_in">local</span>/webserver/mysql/ --<span class="built_in">enable</span>-assembler --with-extra-charsets=complex --<span class="built_in">enable</span>-thread-safe-client --with-big-tables --with-readline --with-ssl --with-embedded-server --<span class="built_in">enable</span>-local-infile</div><div class="line">make &amp;&amp; make install</div><div class="line">chmod +w /usr/<span class="built_in">local</span>/webserver/mysql</div><div class="line">chown -R mysql:mysql /usr/<span class="built_in">local</span>/webserver/mysql</div><div class="line">cp support-files/my-medium.cnf /usr/<span class="built_in">local</span>/webserver/mysql/my.cnf</div><div class="line"><span class="built_in">cd</span> ../</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;附：以下为附加步骤，如果你想在这台服务器上运行MySQL数据库，则执行以下两步。如果你只是希望让PHP支持MySQL扩展库，能够连接其他服务器上的MySQL数据库，那么，以下两步无需执行。</p>
<ul>
<li>以mysql用户帐号的身份建立数据表：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">/usr/<span class="built_in">local</span>/webserver/mysql/bin/mysql_install_db --defaults-file=/usr/<span class="built_in">local</span>/webserver/mysql/my.cnf --basedir=/usr/<span class="built_in">local</span>/webserver/mysql --datadir=/usr/<span class="built_in">local</span>/webserver/mysql/data --user=mysql --pid-file=/usr/<span class="built_in">local</span>/webserver/mysql/mysql.pid --skip-locking --port=3306 --socket=/tmp/mysql.sock</div></pre></td></tr></table></figure>
<ul>
<li>启动MySQL（最后的&amp;表示在后台运行）</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">/bin/sh /usr/local/webserver/mysql/bin/mysqld_safe --defaults-file=/usr/local/webserver/mysql/my.cnf &amp;</div></pre></td></tr></table></figure>
<ol>
<li>编译安装PHP（FastCGI模式）</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">tar zxvf php-5.2.6.tar.gz</div><div class="line">gzip -<span class="built_in">cd</span> php-5.2.6-fpm-0.5.8.diff.gz | patch -d php-5.2.6 -p1</div><div class="line"><span class="built_in">cd</span> php-5.2.6/</div><div class="line">./configure --prefix=/usr/<span class="built_in">local</span>/webserver/php --with-config-file-path=/usr/<span class="built_in">local</span>/webserver/php/etc --with-mysql=/usr/<span class="built_in">local</span>/webserver/mysql --with-mysqli=/usr/<span class="built_in">local</span>/webserver/mysql/bin/mysql_config --with-iconv-dir=/usr/<span class="built_in">local</span> --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --<span class="built_in">enable</span>-xml --<span class="built_in">disable</span>-rpath --<span class="built_in">enable</span>-discard-path --<span class="built_in">enable</span>-safe-mode --<span class="built_in">enable</span>-bcmath --<span class="built_in">enable</span>-shmop --<span class="built_in">enable</span>-sysvsem --<span class="built_in">enable</span>-inline-optimization --with-curl --with-curlwrappers --<span class="built_in">enable</span>-mbregex --<span class="built_in">enable</span>-fastcgi --<span class="built_in">enable</span>-fpm --<span class="built_in">enable</span>-force-cgi-redirect --<span class="built_in">enable</span>-mbstring --with-mcrypt --with-gd --<span class="built_in">enable</span>-gd-native-ttf --with-openssl</div><div class="line">sed -i <span class="string">'s#-lz -lm -lxml2 -lz -lm -lxml2 -lz -lm -lcrypt#&amp; -liconv#'</span> Makefile</div><div class="line">make</div><div class="line">make install</div><div class="line">cp php.ini-dist /usr/<span class="built_in">local</span>/webserver/php/etc/php.ini</div><div class="line"><span class="built_in">cd</span> ../</div></pre></td></tr></table></figure>
<ol>
<li>编译安装PHP5扩展模块</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">tar zxvf memcache-2.2.3.tgz</div><div class="line"><span class="built_in">cd</span> memcache-2.2.3/</div><div class="line">/usr/<span class="built_in">local</span>/webserver/php/bin/phpize</div><div class="line">./configure --with-php-config=/usr/<span class="built_in">local</span>/webserver/php/bin/php-config</div><div class="line">make</div><div class="line">make install</div><div class="line"><span class="built_in">cd</span> ../tar jxvf eaccelerator-0.9.5.3.tar.bz2</div><div class="line"><span class="built_in">cd</span> eaccelerator-0.9.5.3/</div><div class="line">/usr/<span class="built_in">local</span>/webserver/php/bin/phpize</div><div class="line">./configure --<span class="built_in">enable</span>-eaccelerator=shared --with-php-config=/usr/<span class="built_in">local</span>/webserver/php/bin/php-config</div><div class="line">make</div><div class="line">make install</div><div class="line"><span class="built_in">cd</span> ../</div></pre></td></tr></table></figure>
<ol>
<li>修改php.ini文件</li>
</ol>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;手工修改：查找/usr/local/webserver/php/etc/php.ini中的</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">extension_dir = <span class="string">"./"</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;修改为</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">extension_dir = <span class="string">"/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20060613/"</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;并在此行后增加以下几行，然后保存：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">extension = <span class="string">"memcache.so"</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;再查找</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">output_buffering = Off</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;修改为</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">output_buffering = On</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;自动修改：若嫌手工修改麻烦，可执行以下shell命令，自动完成对php.ini文件的修改：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">sed -i <span class="string">'s#extension_dir = "./"#extension_dir = "/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20060613/"/nextension = "memcache.so"/n#'</span> /usr/<span class="built_in">local</span>/webserver/php/etc/php.ini</div><div class="line">sed -i <span class="string">'s#output_buffering = Off#output_buffering = On#'</span> /usr/<span class="built_in">local</span>/webserver/php/etc/php.ini</div><div class="line">    6、配置eAccelerator加速PHP：</div><div class="line">mkdir -p /usr/<span class="built_in">local</span>/webserver/eaccelerator_cache</div><div class="line">vi /usr/<span class="built_in">local</span>/webserver/php/etc/php.ini</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;按shift+g键跳到配置文件的最末尾，加上以下配置信息：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">[eaccelerator]</div><div class="line">zend_extension=<span class="string">"/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20060613/eaccelerator.so"</span></div><div class="line">eaccelerator.shm_size=<span class="string">"128"</span></div><div class="line">eaccelerator.cache_dir=<span class="string">"/usr/local/webserver/eaccelerator_cache"</span></div><div class="line">eaccelerator.enable=<span class="string">"1"</span></div><div class="line">eaccelerator.optimizer=<span class="string">"1"</span></div><div class="line">eaccelerator.check_mtime=<span class="string">"1"</span></div><div class="line">eaccelerator.debug=<span class="string">"0"</span></div><div class="line">eaccelerator.filter=<span class="string">""</span></div><div class="line">eaccelerator.shm_max=<span class="string">"0"</span></div><div class="line">eaccelerator.shm_ttl=<span class="string">"300"</span></div><div class="line">eaccelerator.shm_prune_period=<span class="string">"120"</span></div><div class="line">eaccelerator.shm_only=<span class="string">"0"</span></div><div class="line">eaccelerator.compress=<span class="string">"1"</span></div><div class="line">eaccelerator.compress_level=<span class="string">"9"</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;修改配置文件：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">vi /etc/sysctl.conf</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;输入以下内容：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">kernel.shmmax = 134217728</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;然后执行以下命令使配置生效：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">/sbin/sysctl -p</div></pre></td></tr></table></figure>
<ol>
<li>创建www用户和组，以及供blog.s135.com和www.s135.com两个虚拟主机使用的目录：</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">/usr/sbin/groupadd www -g 48</div><div class="line">/usr/sbin/useradd -u 48 -g www www</div><div class="line">mkdir -p /data0/htdocs/blog</div><div class="line">chmod +w /data0/htdocs/blog</div><div class="line">chown -R www:www /data0/htdocs/blog</div><div class="line">mkdir -p /data0/htdocs/www</div><div class="line">chmod +w /data0/htdocs/www</div><div class="line">chown -R www:www /data0/htdocs/www</div></pre></td></tr></table></figure>
<ol>
<li>创建php-fpm配置文件（php-fpm是为PHP打的一个FastCGI管理补丁，可以平滑变更php.ini配置而无需重启php-cgi）：</li>
</ol>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在/usr/local/webserver/php/etc/目录中创建php-fpm.conf文件：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">rm -f /usr/<span class="built_in">local</span>/webserver/php/etc/php-fpm.conf</div><div class="line">vi /usr/<span class="built_in">local</span>/webserver/php/etc/php-fpm.conf</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;输入以下内容（如果安装 Nginx + PHP 用于程序调试，请将</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&lt;value name=<span class="string">"display_errors"</span>&gt;0&lt;/value&gt;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;改为</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&lt;value name=<span class="string">"display_errors"</span>&gt;1&lt;/value&gt;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;以便显示PHP错误信息，否则，Nginx 会报状态为500的空白错误页）：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div></pre></td><td class="code"><pre><div class="line">All relative paths <span class="keyword">in</span> this config are relative to php<span class="string">'s install prefix </span></div><div class="line"><span class="string">&lt;section name="global_options"&gt;</span></div><div class="line"><span class="string">Pid file  </span></div><div class="line"><span class="string">&lt;value name="pid_file"&gt;/usr/local/webserver/php/logs/php-fpm.pid&lt;/value&gt;</span></div><div class="line"><span class="string">Error log file  </span></div><div class="line"><span class="string">&lt;value name="error_log"&gt;/usr/local/webserver/php/logs/php-fpm.log&lt;/value&gt;</span></div><div class="line"><span class="string">Log level  </span></div><div class="line"><span class="string">&lt;value name="log_level"&gt;notice&lt;/value&gt;</span></div><div class="line"><span class="string">When this amount of php processes exited with SIGSEGV or SIGBUS ...  </span></div><div class="line"><span class="string">&lt;value name="emergency_restart_threshold"&gt;10&lt;/value&gt;</span></div><div class="line"><span class="string">... in a less than this interval of time, a graceful restart will be initiated.  </span></div><div class="line"><span class="string">Useful to work around accidental curruptions in accelerator'</span>s shared memory.  </div><div class="line">&lt;value name=<span class="string">"emergency_restart_interval"</span>&gt;1m&lt;/value&gt;</div><div class="line">Time <span class="built_in">limit</span> on waiting child<span class="string">'s reaction on signals from master  </span></div><div class="line"><span class="string">&lt;value name="process_control_timeout"&gt;5s&lt;/value&gt;</span></div><div class="line"><span class="string">Set to '</span>no<span class="string">' to debug fpm  </span></div><div class="line"><span class="string">&lt;value name="daemonize"&gt;yes&lt;/value&gt;</span></div><div class="line"><span class="string">&lt;/section&gt;</span></div><div class="line"><span class="string">&lt;workers&gt;</span></div><div class="line"><span class="string">&lt;section name="pool"&gt;</span></div><div class="line"><span class="string">Name of pool. Used in logs and stats.  </span></div><div class="line"><span class="string">&lt;value name="name"&gt;default&lt;/value&gt;</span></div><div class="line"><span class="string">Address to accept fastcgi requests on.  </span></div><div class="line"><span class="string">Valid syntax is '</span>ip.ad.re.ss:port<span class="string">' or just '</span>port<span class="string">' or '</span>/path/to/unix/socket<span class="string">'  </span></div><div class="line"><span class="string">&lt;value name="listen_address"&gt;127.0.0.1:9000&lt;/value&gt;</span></div><div class="line"><span class="string">&lt;value name="listen_options"&gt;</span></div><div class="line"><span class="string">Set listen(2) backlog  </span></div><div class="line"><span class="string">&lt;value name="backlog"&gt;-1&lt;/value&gt;</span></div><div class="line"><span class="string">Set permissions for unix socket, if one used.  </span></div><div class="line"><span class="string">In Linux read/write permissions must be set in order to allow connections from web server.  </span></div><div class="line"><span class="string">Many BSD-derrived systems allow connections regardless of permissions.  </span></div><div class="line"><span class="string">&lt;value name="owner"&gt;&lt;/value&gt;</span></div><div class="line"><span class="string">&lt;value name="group"&gt;&lt;/value&gt;</span></div><div class="line"><span class="string">&lt;value name="mode"&gt;0666&lt;/value&gt;</span></div><div class="line"><span class="string">&lt;/value&gt;</span></div><div class="line"><span class="string">Additional php.ini defines, specific to this pool of workers.  </span></div><div class="line"><span class="string">&lt;value name="php_defines"&gt;</span></div><div class="line"><span class="string">&lt;value name="sendmail_path"&gt;/usr/sbin/sendmail -t -i&lt;/value&gt;</span></div><div class="line"><span class="string">&lt;value name="display_errors"&gt;0&lt;/value&gt;</span></div><div class="line"><span class="string">&lt;/value&gt;</span></div><div class="line"><span class="string">Unix user of processes  </span></div><div class="line"><span class="string">&lt;value name="user"&gt;www&lt;/value&gt;</span></div><div class="line"><span class="string">Unix group of processes  </span></div><div class="line"><span class="string">&lt;value name="group"&gt;www&lt;/value&gt;</span></div><div class="line"><span class="string">Process manager settings  </span></div><div class="line"><span class="string">&lt;value name="pm"&gt;</span></div><div class="line"><span class="string">Sets style of controling worker process count.  </span></div><div class="line"><span class="string">Valid values are '</span>static<span class="string">' and '</span>apache-like<span class="string">'  </span></div><div class="line"><span class="string">&lt;value name="style"&gt;static&lt;/value&gt;</span></div><div class="line"><span class="string">Sets the limit on the number of simultaneous requests that will be served.  </span></div><div class="line"><span class="string">Equivalent to Apache MaxClients directive.  </span></div><div class="line"><span class="string">Equivalent to PHP_FCGI_CHILDREN environment in original php.fcgi  </span></div><div class="line"><span class="string">Used with any pm_style.  </span></div><div class="line"><span class="string">&lt;value name="max_children"&gt;200&lt;/value&gt;</span></div><div class="line"><span class="string">Settings group for '</span>apache-like<span class="string">' pm style  </span></div><div class="line"><span class="string">&lt;value name="apache_like"&gt;</span></div><div class="line"><span class="string">Sets the number of server processes created on startup.  </span></div><div class="line"><span class="string">Used only when '</span>apache-like<span class="string">' pm_style is selected  </span></div><div class="line"><span class="string">&lt;value name="StartServers"&gt;20&lt;/value&gt;</span></div><div class="line"><span class="string">Sets the desired minimum number of idle server processes.  </span></div><div class="line"><span class="string">Used only when '</span>apache-like<span class="string">' pm_style is selected  </span></div><div class="line"><span class="string">&lt;value name="MinSpareServers"&gt;5&lt;/value&gt;</span></div><div class="line"><span class="string">Sets the desired maximum number of idle server processes.  </span></div><div class="line"><span class="string">Used only when '</span>apache-like<span class="string">' pm_style is selected  </span></div><div class="line"><span class="string">&lt;value name="MaxSpareServers"&gt;250&lt;/value&gt;</span></div><div class="line"><span class="string">&lt;/value&gt;</span></div><div class="line"><span class="string">&lt;/value&gt;</span></div><div class="line"><span class="string">Time limit on waiting execution of single request  </span></div><div class="line"><span class="string">Should be used when '</span>max_execution_time<span class="string">' ini option does not terminate execution for some reason  </span></div><div class="line"><span class="string">&lt;value name="request_execution_timeout"&gt;31s&lt;/value&gt;</span></div><div class="line"><span class="string">Set open file desc rlimit  </span></div><div class="line"><span class="string">&lt;value name="rlimit_files"&gt;51200&lt;/value&gt;</span></div><div class="line"><span class="string">Set max core size rlimit  </span></div><div class="line"><span class="string">&lt;value name="rlimit_core"&gt;0&lt;/value&gt;</span></div><div class="line"><span class="string">Chroot to this directory at the start  </span></div><div class="line"><span class="string">&lt;value name="chroot"&gt;&lt;/value&gt;</span></div><div class="line"><span class="string">Chdir to this directory at the start  </span></div><div class="line"><span class="string">&lt;value name="chdir"&gt;&lt;/value&gt;</span></div><div class="line"><span class="string">Redirect workers'</span> stdout and stderr into main error <span class="built_in">log</span>.  </div><div class="line">If not <span class="built_in">set</span>, they will be redirected to /dev/null, according to FastCGI specs  </div><div class="line">&lt;value name=<span class="string">"catch_workers_output"</span>&gt;yes&lt;/value&gt;</div><div class="line">How much requests each process should execute before respawn.  </div><div class="line">Useful to work around memory leaks <span class="keyword">in</span> 3rd party libraries.  </div><div class="line">For endless request processing please specify 0  </div><div class="line">Equivalent to PHP_FCGI_MAX_REQUESTS  </div><div class="line">&lt;value name=<span class="string">"max_requests"</span>&gt;51200&lt;/value&gt;</div><div class="line">Comma separated list of ipv4 addresses of FastCGI clients that allowed to connect.  </div><div class="line">Equivalent to FCGI_WEB_SERVER_ADDRS environment <span class="keyword">in</span> original php.fcgi (5.2.2+)  </div><div class="line">Makes sense only with AF_INET listening socket.  </div><div class="line">&lt;value name=<span class="string">"allowed_clients"</span>&gt;127.0.0.1&lt;/value&gt;</div><div class="line">Pass environment variables like LD_LIBRARY_PATH  </div><div class="line">All <span class="variable">$VARIABLEs</span> are taken from current environment  </div><div class="line">&lt;value name=<span class="string">"environment"</span>&gt;</div><div class="line">&lt;value name=<span class="string">"HOSTNAME"</span>&gt;<span class="variable">$HOSTNAME</span>&lt;/value&gt;</div><div class="line">&lt;value name=<span class="string">"PATH"</span>&gt;/usr/<span class="built_in">local</span>/bin:/usr/bin:/bin&lt;/value&gt;</div><div class="line">&lt;value name=<span class="string">"TMP"</span>&gt;/tmp&lt;/value&gt;</div><div class="line">&lt;value name=<span class="string">"TMPDIR"</span>&gt;/tmp&lt;/value&gt;</div><div class="line">&lt;value name=<span class="string">"TEMP"</span>&gt;/tmp&lt;/value&gt;</div><div class="line">&lt;value name=<span class="string">"OSTYPE"</span>&gt;<span class="variable">$OSTYPE</span>&lt;/value&gt;</div><div class="line">&lt;value name=<span class="string">"MACHTYPE"</span>&gt;<span class="variable">$MACHTYPE</span>&lt;/value&gt;</div><div class="line">&lt;value name=<span class="string">"MALLOC_CHECK_"</span>&gt;2&lt;/value&gt;</div><div class="line">&lt;/value&gt;</div><div class="line">&lt;/section&gt;</div><div class="line">&lt;/workers&gt;</div><div class="line">&lt;/configuration&gt;</div></pre></td></tr></table></figure>
<ol>
<li>启动php-cgi进程，监听127.0.0.1的9000端口，进程数为200（如果服务器内存小于3GB，可以只开启64个进程），用户为www：</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">ulimit</span> -SHn 51200</div><div class="line">/usr/<span class="built_in">local</span>/webserver/php/sbin/php-fpm start</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;注：/usr/local/webserver/php/sbin/php-fpm还有其他参数，包括：start|stop|quit|restart|reload|logrotate，修改php.ini后不重启php-cgi，重新加载  配置文件使用reload。</p>
<h2 id="三、安装Nginx-0-7-14"><a href="#三、安装Nginx-0-7-14" class="headerlink" title="三、安装Nginx 0.7.14"></a>三、安装Nginx 0.7.14</h2><ol>
<li>安装Nginx所需的pcre库：</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">tar zxvf pcre-7.7.tar.gz</div><div class="line"><span class="built_in">cd</span> pcre-7.7/</div><div class="line">./configure</div><div class="line">make &amp;&amp; make install</div><div class="line"><span class="built_in">cd</span> ../</div></pre></td></tr></table></figure>
<ol>
<li>安装Nginx</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">tar zxvf nginx-0.7.14.tar.gz</div><div class="line"><span class="built_in">cd</span> nginx-0.7.14/</div><div class="line">./configure --user=www --group=www --prefix=/usr/<span class="built_in">local</span>/webserver/nginx --with-http_stub_status_module --with-http_ssl_module</div><div class="line">make &amp;&amp; make install</div><div class="line"><span class="built_in">cd</span> ../</div></pre></td></tr></table></figure>
<ol>
<li>创建Nginx日志目录</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mkdir -p /data1/logs</div><div class="line">chmod +w /data1/logs</div><div class="line">chown -R www:www /data1/logs</div></pre></td></tr></table></figure>
<ol>
<li>创建Nginx配置文件</li>
</ol>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在/usr/local/webserver/nginx/conf/目录中创建nginx.conf文件：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">rm -f /usr/<span class="built_in">local</span>/webserver/nginx/conf/nginx.conf</div><div class="line">vi /usr/<span class="built_in">local</span>/webserver/nginx/conf/nginx.conf</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;输入以下内容：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div></pre></td><td class="code"><pre><div class="line">user www www;</div><div class="line">worker_processes 8;</div><div class="line">error_log /data1/logs/nginx_error.log crit;</div><div class="line">pid /usr/<span class="built_in">local</span>/webserver/nginx/nginx.pid;</div><div class="line"><span class="comment">#Specifies the value for maximum file descriptors that can be opened by this process.</span></div><div class="line">worker_rlimit_nofile 51200;</div><div class="line">events</div><div class="line">&#123;</div><div class="line"> use epoll;</div><div class="line"> worker_connections 51200;</div><div class="line">&#125;</div><div class="line">http</div><div class="line">&#123;</div><div class="line"> include mime.types;</div><div class="line"> default_type application/octet-stream;</div><div class="line"><span class="comment">#charset gb2312;</span></div><div class="line">server_names_hash_bucket_size 128;</div><div class="line">client_header_buffer_size 32k;</div><div class="line">large_client_header_buffers 4 32k;</div><div class="line">sendfile on;</div><div class="line">tcp_nopush on;</div><div class="line">keepalive_timeout 60;</div><div class="line">tcp_nodelay on;</div><div class="line">fastcgi_connect_timeout 300;</div><div class="line">fastcgi_send_timeout 300;</div><div class="line">fastcgi_read_timeout 300;</div><div class="line">fastcgi_buffer_size 64k;</div><div class="line">fastcgi_buffers 4 64k;</div><div class="line">fastcgi_busy_buffers_size 128k;</div><div class="line">fastcgi_temp_file_write_size 128k;</div><div class="line">gzip on;</div><div class="line">gzip_min_length 1k;</div><div class="line">gzip_buffers 4 16k;</div><div class="line">gzip_http_version 1.0;</div><div class="line">gzip_comp_level 2;</div><div class="line">gzip_types text/plain application/x-JavaScript text/css application/xml;</div><div class="line">gzip_vary on;</div><div class="line"><span class="comment">#limit_zone crawler $binary_remote_addr 10m;</span></div><div class="line">server</div><div class="line">&#123;</div><div class="line">listen 80;</div><div class="line">server_name blog.s135.com;</div><div class="line">index index.html index.htm index.php;</div><div class="line">root /data0/htdocs/blog;</div><div class="line"><span class="comment">#limit_conn crawler 20;</span></div><div class="line">location ~ .*/.(php|php5)?$</div><div class="line">&#123;</div><div class="line"><span class="comment">#fastcgi_pass unix:/tmp/php-cgi.sock;</span></div><div class="line">fastcgi_pass 127.0.0.1:9000;</div><div class="line">fastcgi_index index.php;</div><div class="line">include fcgi.conf;</div><div class="line">&#125;</div><div class="line">location ~ .*/.(gif|jpg|jpeg|png|bmp|swf)$</div><div class="line">&#123;</div><div class="line">expires 30d;</div><div class="line">&#125;</div><div class="line">location ~ .*/.(js|css)?$</div><div class="line">&#123;</div><div class="line">expires 1h;</div><div class="line">&#125;</div><div class="line">log_format access <span class="string">'$remote_addr - $remote_user [$time_local] "$request" '</span></div><div class="line"><span class="string">'$status $body_bytes_sent "$http_referer" '</span></div><div class="line"><span class="string">'"$http_user_agent" $http_x_forwarded_for'</span>;</div><div class="line">access_log /data1/logs/access.log access;</div><div class="line">&#125;</div><div class="line">server</div><div class="line">&#123;</div><div class="line">listen 80;</div><div class="line">server_name www.s135.com;</div><div class="line">index index.html index.htm index.php;</div><div class="line">root /data0/htdocs/www;</div><div class="line">location ~ .*/.(php|php5)?$</div><div class="line">&#123;</div><div class="line"><span class="comment">#fastcgi_pass unix:/tmp/php-cgi.sock;</span></div><div class="line">fastcgi_pass 127.0.0.1:9000;</div><div class="line">fastcgi_index index.php;</div><div class="line">include fcgi.conf;</div><div class="line">&#125;</div><div class="line">log_format wwwlogs <span class="string">'$remote_addr - $remote_user [$time_local] "$request" '</span></div><div class="line"><span class="string">'$status $body_bytes_sent "$http_referer" '</span></div><div class="line"><span class="string">'"$http_user_agent" $http_x_forwarded_for'</span>;</div><div class="line">access_log /data1/logs/wwwlogs.log wwwlogs;</div><div class="line">&#125;</div><div class="line">server</div><div class="line">&#123;</div><div class="line">listen 80;</div><div class="line">server_name status.blog.s135.com;</div><div class="line">location / &#123;</div><div class="line">stub_status on;</div><div class="line">access_log off;</div><div class="line">&#125;</div><div class="line">&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在/usr/local/webserver/nginx/conf/目录中创建fcgi.conf文件：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">vi /usr/<span class="built_in">local</span>/webserver/nginx/conf/fcgi.conf</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;输入以下内容：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">fastcgi_param GATEWAY_INTERFACE CGI/1.1;</div><div class="line">fastcgi_param SERVER_SOFTWARE nginx;fastcgi_param QUERY_STRING <span class="variable">$query_string</span>;</div><div class="line">fastcgi_param REQUEST_METHOD <span class="variable">$request_method</span>;</div><div class="line">fastcgi_param CONTENT_TYPE <span class="variable">$content_type</span>;</div><div class="line">fastcgi_param CONTENT_LENGTH <span class="variable">$content_length</span>;</div><div class="line">fastcgi_param SCRIPT_FILENAME <span class="variable">$document_root</span><span class="variable">$fastcgi_script_name</span>;</div><div class="line">fastcgi_param SCRIPT_NAME <span class="variable">$fastcgi_script_name</span>;</div><div class="line">fastcgi_param REQUEST_URI <span class="variable">$request_uri</span>;</div><div class="line">fastcgi_param DOCUMENT_URI <span class="variable">$document_uri</span>;</div><div class="line">fastcgi_param DOCUMENT_ROOT <span class="variable">$document_root</span>;</div><div class="line">fastcgi_param SERVER_PROTOCOL <span class="variable">$server_protocol</span>;</div><div class="line">fastcgi_param REMOTE_ADDR <span class="variable">$remote_addr</span>;</div><div class="line">fastcgi_param REMOTE_PORT <span class="variable">$remote_port</span>;</div><div class="line">fastcgi_param SERVER_ADDR <span class="variable">$server_addr</span>;</div><div class="line">fastcgi_param SERVER_PORT <span class="variable">$server_port</span>;</div><div class="line">fastcgi_param SERVER_NAME <span class="variable">$server_name</span>;</div><div class="line"><span class="comment"># PHP only, required if PHP was built with --enable-force-cgi-redirect</span></div><div class="line">fastcgi_param REDIRECT_STATUS 200;</div></pre></td></tr></table></figure>
<ol>
<li>启动Nginx</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">ulimit</span> -SHn 51200</div><div class="line">/usr/<span class="built_in">local</span>/webserver/nginx/sbin/nginx</div></pre></td></tr></table></figure>
<h2 id="四、配置开机自动启动Nginx-PHP"><a href="#四、配置开机自动启动Nginx-PHP" class="headerlink" title="四、配置开机自动启动Nginx + PHP"></a>四、配置开机自动启动Nginx + PHP</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">vi /etc/rc.local</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在末尾增加以下内容：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">ulimit</span> -SHn 51200</div><div class="line">/usr/<span class="built_in">local</span>/webserver/php/sbin/php-fpm start</div><div class="line">/usr/<span class="built_in">local</span>/webserver/nginx/sbin/nginx</div></pre></td></tr></table></figure>
<h2 id="五、优化Linux内核参数"><a href="#五、优化Linux内核参数" class="headerlink" title="五、优化Linux内核参数"></a>五、优化Linux内核参数</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">vi /etc/sysctl.conf</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在末尾增加以下内容：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">net.ipv4.tcp_fin_timeout = 30</div><div class="line">net.ipv4.tcp_keepalive_time = 300</div><div class="line">net.ipv4.tcp_syncookies = 1</div><div class="line">net.ipv4.tcp_tw_reuse = 1</div><div class="line">net.ipv4.tcp_tw_recycle = 1</div><div class="line">net.ipv4.ip_local_port_range = 5000 65000</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;使配置立即生效：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">/sbin/sysctl -p</div></pre></td></tr></table></figure>
<h2 id="六、在不停止Nginx服务的情况下平滑变更Nginx配置"><a href="#六、在不停止Nginx服务的情况下平滑变更Nginx配置" class="headerlink" title="六、在不停止Nginx服务的情况下平滑变更Nginx配置"></a>六、在不停止Nginx服务的情况下平滑变更Nginx配置</h2><ol>
<li>修改/usr/local/webserver/nginx/conf/nginx.conf配置文件后，请执行以下命令检查配置文件是否正确：</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">/usr/<span class="built_in">local</span>/webserver/nginx/sbin/nginx -t</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果屏幕显示以下两行信息，说明配置文件正确：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">the configuration file /usr/<span class="built_in">local</span>/webserver/nginx/conf/nginx.conf syntax is ok</div><div class="line">the configuration file /usr/<span class="built_in">local</span>/webserver/nginx/conf/nginx.conf was tested successfully</div></pre></td></tr></table></figure>
<ol>
<li>这时，输入以下命令查看Nginx主进程号：</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">ps -ef | grep <span class="string">"nginx: master process"</span> | grep -v <span class="string">"grep"</span> | awk -F <span class="string">' '</span> <span class="string">'&#123;print $2&#125;'</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;屏幕显示的即为Nginx主进程号，例如：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">6302</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这时，执行以下命令即可使修改过的Nginx配置文件生效：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">kill</span> -HUP 6302</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;或者无需这么麻烦，找到Nginx的Pid文件：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">kill</span> -HUP `cat /usr/<span class="built_in">local</span>/webserver/nginx/nginx.pid`</div></pre></td></tr></table></figure>

	

	

</article>




	<article>
	
		<h1><a href="/2017/10/12/Nginx/26. nginx针对请求的uri来代理/">nginx针对请求的uri来代理</a></h1>
	
	<div class="article__infos">
		<span class="article__date">2017-10-12</span><br />
		
		
			<span class="article__tags">
			  	<a class="article__tag-link" href="/tags/LNMP/">LNMP</a> <a class="article__tag-link" href="/tags/Nginx/">Nginx</a>
			</span>
		
	</div>

	

	
		<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;场景：1台nginx去代理4台apache</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;需求：根据不同的请求uri 代理到不同的apache</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;nginx的配置文件为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line">upstream aa.com &#123; </div><div class="line">                  server 192.168.0.121;</div><div class="line">                  server 192.168.0.122; </div><div class="line">  &#125;</div><div class="line">upstream bb.com &#123; </div><div class="line">                  server 192.168.0.123;</div><div class="line">                  server 192.168.0.124;</div><div class="line">    &#125;</div><div class="line">server &#123;</div><div class="line">    listen 80;</div><div class="line">    server_name www.abc.com;</div><div class="line">    location ~ aa.php</div><div class="line">    &#123;</div><div class="line">        proxy_pass http://aa.com/;</div><div class="line">        proxy_set_header Host <span class="variable">$host</span>;</div><div class="line">        proxy_set_header X-Real-IP <span class="variable">$remote_addr</span>;</div><div class="line">        proxy_set_header X-Forwarded-For <span class="variable">$proxy_add_x_forwarded_for</span>;</div><div class="line">    &#125;</div><div class="line">    location ~ bb.php</div><div class="line">    &#123;</div><div class="line">        proxy_pass http://bb.com/;</div><div class="line">        proxy_set_header Host <span class="variable">$host</span>;</div><div class="line">        proxy_set_header X-Real-IP <span class="variable">$remote_addr</span>;</div><div class="line">        proxy_set_header X-Forwarded-For <span class="variable">$proxy_add_x_forwarded_for</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>

	

	

</article>




	<article>
	
		<h1><a href="/2017/10/12/Nginx/25. nginx代理--根据访问的目录来区分后端的web/">nginx代理--根据访问的目录来区分后端的web</a></h1>
	
	<div class="article__infos">
		<span class="article__date">2017-10-12</span><br />
		
		
			<span class="article__tags">
			  	<a class="article__tag-link" href="/tags/LNMP/">LNMP</a> <a class="article__tag-link" href="/tags/Nginx/">Nginx</a>
			</span>
		
	</div>

	

	
		<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;需求： 当请求的目录是 /aaa/ 则把请求发送到机器a，当请求的目录为/bbb/则把请求发送到机器b，除了目录/aaa/与目录/bbb/外，其他的请求发送到机器b</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;的配置文件内容为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div></pre></td><td class="code"><pre><div class="line">upstream aaa.com</div><div class="line">&#123;</div><div class="line">        server 192.168.111.6;</div><div class="line">&#125;</div><div class="line">        upstream bbb.com</div><div class="line">&#123;</div><div class="line">        server 192.168.111.20;</div><div class="line">&#125;</div><div class="line">server &#123;</div><div class="line">        listen 80;</div><div class="line">        server_name li.com;</div><div class="line">        location /aaa/</div><div class="line">        &#123;</div><div class="line">        proxy_pass http://aaa.com/aaa/;</div><div class="line">        proxy_set_header Host <span class="variable">$host</span>;</div><div class="line">        proxy_set_header X-Real-IP <span class="variable">$remote_addr</span>;</div><div class="line">        proxy_set_header X-Forwarded-For <span class="variable">$proxy_add_x_forwarded_for</span>;</div><div class="line">        &#125;</div><div class="line">location /bbb/</div><div class="line">        &#123;</div><div class="line">        proxy_pass http://bbb.com/bbb/;</div><div class="line">        proxy_set_header Host <span class="variable">$host</span>;</div><div class="line">        proxy_set_header X-Real-IP <span class="variable">$remote_addr</span>;</div><div class="line">        proxy_set_header X-Forwarded-For <span class="variable">$proxy_add_x_forwarded_for</span>;</div><div class="line">        &#125;</div><div class="line">location /</div><div class="line">        &#123;</div><div class="line">        proxy_pass http://bbb.com/;</div><div class="line">        proxy_set_header Host <span class="variable">$host</span>;</div><div class="line">        proxy_set_header X-Real-IP <span class="variable">$remote_addr</span>;</div><div class="line">        proxy_set_header X-Forwarded-For <span class="variable">$proxy_add_x_forwarded_for</span>;</div><div class="line">        &#125;</div><div class="line">       &#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;1. 以上配置文件中的 aaa.com 以及 bbb.com 都是自定义的，随便写。</p>
<ol>
<li>upstream 中的server 可以写多个，例如</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">upstream aaa.com </div><div class="line">&#123;</div><div class="line">    server 192.168.111.6;</div><div class="line">    server 192.168.111.4;</div><div class="line">    server 192.168.111.5;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ol>
<li><p>proxy_pass <a href="http://aaa.com/aaa/" target="_blank" rel="external">http://aaa.com/aaa/</a>  这里必须要加这个目录，不然就访问到根目录了。</p>
</li>
<li><p>实际上，上述配置文件中， localtion /bbb/ 部分是可以省略掉的，因为后边的 location /  已经包含了/bbb/，所以即使我们不去定义  localtion /bbb/ 也是会访问到 bbb.com 的。</p>
</li>
</ol>

	

	

</article>




	<article>
	
		<h1><a href="/2017/10/12/Nginx/24. Nginx的rewrite应用/">Nginx的rewrite应用</a></h1>
	
	<div class="article__infos">
		<span class="article__date">2017-10-12</span><br />
		
		
			<span class="article__tags">
			  	<a class="article__tag-link" href="/tags/LNMP/">LNMP</a> <a class="article__tag-link" href="/tags/Nginx/">Nginx</a>
			</span>
		
	</div>

	

	
		<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Rewrite主要的功能是实现URL重写，Nginx 的 Rewrite 规则采用 PCRE Perl 兼容正则表达式的语法进行规则匹配，如相使用 Nginx 的 Rewrite 功能，在编译 Nginx 前要编译安装 PCRE 库。</p>
<h2 id="一、Nginx使用if进行条件匹配"><a href="#一、Nginx使用if进行条件匹配" class="headerlink" title="一、Nginx使用if进行条件匹配"></a>一、Nginx使用if进行条件匹配</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx可以用if进行条件匹配，语法规则类似C</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> （条件）&#123;...&#125; ( 可用于： server,location )</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;检查一个条件是否符合，如果条件符合，则执行大括号内的语句。不支持嵌套，不支持多条件 &amp;&amp; || </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;例如：if ($http_user_agent ~ MSIE) {rewrite  ^(.*)$  /msie/$1  break;}</p>
<ol>
<li>正则表达式匹配，其中：</li>
</ol>
<ul>
<li>~  为区分大小写匹配 </li>
<li>~* 为不区分大小写匹配 </li>
<li>!~和!~*分别为区分大小写不匹配及不区分大小写不匹配</li>
</ul>
<ol>
<li>文件及目录匹配，其中：</li>
</ol>
<ul>
<li>-f和!-f用来判断是否存在文件 </li>
<li>-d和!-d用来判断是否存在目录 </li>
<li>-e和!-e用来判断是否存在文件或目录 </li>
<li>-x和!-x用来判断文件是否可执行</li>
</ul>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;例如：if (!-f $request_filename) {proxy_pass  <a href="http://127.0.0.1;}" target="_blank" rel="external">http://127.0.0.1;}</a></p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Wordpress的重定向规则：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (!-e <span class="variable">$request_filename</span>) &#123;rewrite ^/(index|atom|rsd)\.xml$ http://feed.shunz.net last;rewrite ^([_0-9a-zA-Z-]+)?(/wp-.*) <span class="variable">$2</span> last;rewrite ^([_0-9a-zA-Z-]+)?(/.*\.php)$ <span class="variable">$2</span> last;rewrite ^ /index.php last;&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;return ( 可用于： server,location,if )  ## 用于结束规则的执行并反回状态码给客户端。  状态码可以是 ：204/400/402~406/408/410/411/413/416/500~504  </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">location ~ .*\.(sh|bash)?$ &#123;  </div><div class="line">      <span class="built_in">return</span> 403;  </div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;访问的 URL 以 .sh .bash 结尾的，则返回 403 。</p>
<ul>
<li>204  No Content  </li>
<li>400  Bad Request  </li>
<li>402  Payment Required  </li>
<li>403  Forbidden  </li>
<li>404  Not Found  </li>
<li>405  Method Not Allowed  </li>
<li>406  Not Acceptable  </li>
<li>408  Request Timeout  </li>
<li>410  Gone  </li>
<li>411  Length Required  </li>
<li>413  Request Entity Too Large  </li>
<li>416  Requested Range Not Satisfiable  </li>
<li>500  Internal Server Error  </li>
<li>501  Not Implemented  </li>
<li>502  Bad Gateway  </li>
<li>503  Service Unavailable  </li>
<li>504  Gateway Timeout </li>
</ul>
<h2 id="二、Nginx使用rewrite"><a href="#二、Nginx使用rewrite" class="headerlink" title="二、Nginx使用rewrite"></a>二、Nginx使用rewrite</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;rewrite ( 可用于： server,location,if ) ## 重写 URL ，或修改字符串。重写 URL 只对相对路径有效，如想对主机名，要使用 if 语句。 </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;例1：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (<span class="variable">$host</span> ~* www\.(.*)) &#123;  </div><div class="line">      <span class="built_in">set</span> <span class="variable">$host_without_www</span> <span class="variable">$1</span>;  </div><div class="line">      rewrite ^(.*)$ http://<span class="variable">$host_without_www</span><span class="variable">$1</span> permanent;  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果替换串以 http:// 开头，将会采用 301 或 302 跳转进行 URL 重定向。 </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;例2：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">rewrite ^/feed/$ http://feed.shunz.net last;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Nginx的Rewrite规则与Apache几乎完全一致，所不同的是最后的flag标记，Nginx的rewrite指令后支持的标记有last，break，redirect，permanent</p>
<ul>
<li>last 相当于Apache里的[L]标记，表示完成rewrite，不再匹配后面的规则 </li>
<li>break ( 可用于： server,location,if ) ## 本条规则匹配完成后，终止匹配，不再匹配后面的规则<br>如：rewrite ^/b/(.*).html /play.php?video=$1 break; </li>
<li>redirect 返回302临时重定向,浏览器会显示跳转后的URL地址</li>
<li>permanent 返回301永久重定向，浏览器会显示跳转后的URL地址</li>
</ul>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;last/break用来实现URL重写，浏览器地址栏的URL不变，但在服务器端访问的路径发生了变化。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;redirect/permanent实现URL跳转，浏览器地址栏URL会显示跳转后的URL。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;使用 alias 指令时必须用 last 标记 ，使用 proxy_pass 指令时要用 break 表示。 last 标记在本条 rewrite 规则执行完毕后，会对其所在 server{….}标签重新发起请 求，而 break 标记则在本条规则匹配完成后，终止匹配。  </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">location /cms/ &#123;  </div><div class="line">      proxy_pass http://test.abc.com;  </div><div class="line">      rewrite <span class="string">"^/cms/(.*)\.html$"</span> /cms/index.html <span class="built_in">break</span>;  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这条规则如果使用 last 会导致死循环。  </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;一般在根 location 中（即 location / {….}）或直接在 server 标签编写 rewrite 规则，推荐使用 last 标记，  </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在非根 location 中 (即 location /cms/ {…}),则使用 break 标记。 </p>
<h2 id="Nginx-document-uri参数的使用"><a href="#Nginx-document-uri参数的使用" class="headerlink" title="Nginx $document_uri参数的使用"></a>Nginx $document_uri参数的使用</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;$document_uri  表示访问的url 现在我的需求是，访问 www.abc.com  请求到 www.abc.com/abc/</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在nginx配置文件中加入</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (<span class="variable">$document_uri</span> !~ <span class="string">'abc'</span>)</div><div class="line">    &#123;</div><div class="line">            rewrite ^/(.*)$ http://www.abc.com/abc/<span class="variable">$1</span> permanent;</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;而不是单独加一句  rewrite ^/(.*)$ <a href="http://www.abc.com/abc/$1" target="_blank" rel="external">http://www.abc.com/abc/$1</a> permanent;</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果只加rewrite 规则，而不限定条件，那么会造成死循环。  会访问到   <a href="http://www.abc.com/abc/abc/abc/abc/" target="_blank" rel="external">http://www.abc.com/abc/abc/abc/abc/</a>….</p>

	

	

</article>




	<article>
	
		<h1><a href="/2017/10/12/Nginx/23. nginx代理/">nginx代理</a></h1>
	
	<div class="article__infos">
		<span class="article__date">2017-10-12</span><br />
		
		
			<span class="article__tags">
			  	<a class="article__tag-link" href="/tags/LNMP/">LNMP</a> <a class="article__tag-link" href="/tags/Nginx/">Nginx</a>
			</span>
		
	</div>

	

	
		<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">[root@lnmp ~]<span class="comment"># vim /usr/local/nginx/conf/vhosts/proxy.conf</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;加入内容：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">server &#123;</div><div class="line">    listen 80;</div><div class="line">    server_name www.baidu.com;</div><div class="line"></div><div class="line">    location / &#123;</div><div class="line">        proxy_pass http://180.97.33.107/;</div><div class="line">        proxy_set_header Host <span class="variable">$host</span>;</div><div class="line">        proxy_set_header X-Real-IP <span class="variable">$remote_addr</span>;</div><div class="line">        proxy_set_header X-Forwarded-For <span class="variable">$proxy_add_x_forwarded_for</span>;</div><div class="line">    &#125;</div><div class="line"><span class="comment"># access_log /home/logs/baidu.access combined;</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;说明：proxy_pass 后面跟要代理机器的 ip 。如果后端的机器有多台，还可以用 upstream 来实现负载均衡，配置如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">upsteam baidu &#123;</div><div class="line">    server 180.97.33.108:80;</div><div class="line">    server 180.97.33.107:80;</div><div class="line">&#125;</div><div class="line">server &#123;</div><div class="line">    listen 80;</div><div class="line">    server_name www.baidu.com;</div><div class="line"></div><div class="line">    location / &#123;</div><div class="line">        proxy_pass http://baidu/;</div><div class="line">        proxy_set_header Host <span class="variable">$host</span>;</div><div class="line">        proxy_set_header X-Real-IP <span class="variable">$remote_addr</span>;</div><div class="line">        proxy_set_header X-Forwarded-For <span class="variable">$proxy_add_x_forwarded_for</span>;</div><div class="line">    &#125;</div><div class="line"><span class="comment"># access_log /home/logs/baidu.access combined;</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;说明： upstream 后面的名字是自定义的，这个名字会放到 proxy_pass 后面。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;还可以代理一个服务器上所有域名，首先在 vhosts 目录下需要建立两个文件，一个是 servername 列表文件，一个是虚拟主机配置文件。两个文件内容分别为</p>
<h2 id="1-servername"><a href="#1-servername" class="headerlink" title="1.servername"></a>1.servername</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">[root@lnmp ~]<span class="comment"># vim /usr/local/nginx/conf/vhosts/servername</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;加入内容：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">server_name www.123.com www.234.com www.345.com;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;就这么简单一行，这个server_name 还可以继续添加</p>
<h2 id="2-虚拟主机配置文件"><a href="#2-虚拟主机配置文件" class="headerlink" title="2.虚拟主机配置文件"></a>2.虚拟主机配置文件</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">[root@lnmp ~]<span class="comment"># vim /usr/local/nginx/conf/vhosts/proxy_all.conf</span></div><div class="line"></div><div class="line">server &#123;</div><div class="line">    listen 80;</div><div class="line">    include vhosts/servername;</div><div class="line">    location / &#123;</div><div class="line">        proxy_pass http://1.2.1.2/;</div><div class="line">        proxy_set_header Host <span class="variable">$host</span>;</div><div class="line">        proxy_set_header X-Real-IP <span class="variable">$remote_addr</span>;</div><div class="line">        proxy_set_header X-Forwarded-For <span class="variable">$proxy_add_x_forwarded_for</span>;</div><div class="line">    &#125;</div><div class="line">    access_log /dev/null;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;include vhosts/servername; 这个文件就是上边那个 servername 列表文件；</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;proxy_pass <a href="http://1.2.1.2/" target="_blank" rel="external">http://1.2.1.2/</a>; 就是需要做代理的服务器 ip 地址 </p>

	

	

</article>




	<article>
	
		<h1><a href="/2017/10/12/Nginx/22. nginx禁止指定user_agent/">nginx禁止指定user_agent</a></h1>
	
	<div class="article__infos">
		<span class="article__date">2017-10-12</span><br />
		
		
			<span class="article__tags">
			  	<a class="article__tag-link" href="/tags/LNMP/">LNMP</a> <a class="article__tag-link" href="/tags/Nginx/">Nginx</a>
			</span>
		
	</div>

	

	
		<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;具体配置如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">location / &#123;</div><div class="line"> <span class="keyword">if</span> (<span class="variable">$http_user_agent</span> ~ <span class="string">'curl|baidu|111111'</span>)</div><div class="line">     &#123;</div><div class="line">         <span class="built_in">return</span> 403;</div><div class="line">     &#125;</div><div class="line"> &#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;把 ~ 改为 ~* 就是不区分大小写。</p>

	

	

</article>





	<span class="different-posts">📖 <a href="/page/25">more posts</a> 📖</span>



	</main>

	<footer class="footer">
	<div class="footer-content">
		
	      <div class="footer__element">
	<p>Hi there, <br />welcome to my Blog glad you found it. Have a look around, will you?</p>
</div>

	    
	      <div class="footer__element">
	<h5>Check out</h5>
	<ul class="footer-links">
		<li class="footer-links__link"><a href="/archives">Archive</a></li>
		
		  <li class="footer-links__link"><a href="/atom.xml">RSS</a></li>
	    
		<li class="footer-links__link"><a href="/about">about page</a></li>
		<li class="footer-links__link"><a href="/tags">Tags</a></li>
		<li class="footer-links__link"><a href="/categories">Categories</a></li>
	</ul>
</div>

	    

		<div class="footer-credit">
			<span>© 2017 失落的乐章 | Powered by <a href="https://hexo.io/">Hexo</a> | Theme <a href="https://github.com/HoverBaum/meilidu-hexo">MeiliDu</a></span>
		</div>

	</div>


</footer>



</body>

</html>
